package com.authine.cloudpivot.ext.quartz.task;

import com.authine.cloudpivot.engine.api.model.scheduler.JobModel;
import com.authine.cloudpivot.engine.enums.type.timer.CallbackType;
import com.authine.cloudpivot.engine.enums.type.timer.SchedulerExecuteType;
import com.authine.cloudpivot.engine.service.scheduler.SchedulerService;
import com.authine.cloudpivot.ext.service.ipml.BlowWhistleEventServiceIpml;
import com.authine.cloudpivot.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;


/**
 * 统一的定时作业,定时执行对应类的方法
 * 定时任务需要使用public 修饰符 其他方法使用private
 */
@Component
@Slf4j
public class UnifiedJob {

    @Autowired
    private SchedulerService schedulerService;




    //定时推送超时未处理待办
    public void timedOutToDo() {
        JobModel jobModel = this.buildJob("timedOutToDo", "0 0/10 * * * ?", BlowWhistleEventServiceIpml.class, "pushTimedOutToDo");
        log.info("开启 定时推送超时未处理待办:{},执行时间规则：{}", jobModel.getName(), jobModel.getCron());

    }


    /**
     * @param jobName    任务名称
     * @param cron       定时任务表达式
     * @param beanName   执行任务类名称
     * @param methodName 执行任务方法名称
     */
    private JobModel buildJob(String jobName, String cron, Class beanName, String methodName) {
        JobModel jobModel = new JobModel();
        jobModel.setName(jobName);
        jobModel.setGroup("unifiedJob");
        jobModel.setExecuteType(SchedulerExecuteType.CYCLE);
        jobModel.setCron(cron);
        jobModel.setCallbackType(CallbackType.JAVA_CODE);
        jobModel.setBeanName(StringUtil.lowerFirst(beanName.getSimpleName()));
        jobModel.setMethodName(methodName);
        LocalDateTime timeMin = LocalDateTime.of(2023, 1, 1, 0, 0, 0);
        LocalDateTime timeMax = timeMin.plusYears(100);
        jobModel.setFireTime(timeMin); //任务执行起始时间
        jobModel.setEndTime(timeMax);  //任务执行结束时间
        //构建定时任务
        schedulerService.updateJob(jobModel.getGroup(), jobModel.getName(), jobModel);
        return jobModel;
    }




}
